package com.buddy.qreport.datasource.service.impl;

import com.alibaba.druid.pool.DruidDataSource;
import com.buddy.qreport.common.mybatis.entity.Page;
import com.buddy.qreport.datasource.dao.IDataSourceMapper;
import com.buddy.qreport.datasource.dynamic.DynamicDataSource;
import com.buddy.qreport.datasource.entity.DataSourceEntity;
import com.buddy.qreport.datasource.service.IDataSourceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

@Slf4j
@Service("QREPORT_DataSourceService")
public class IDataSourceServiceImpl implements IDataSourceService {

    @Autowired
    private IDataSourceMapper dataSourceMapper;


    /**
     * 此处dataSource为DynamicDataSource
     */
    @Autowired
    private DynamicDataSource dynamicDataSource;

    @Override
    public Page<DataSourceEntity> getList(Page page) {

        dataSourceMapper.getList(page);

        return page;
    }

    @Override
    public List<DataSourceEntity> getList() {
        return dataSourceMapper.getList(null);
    }

    @Override
    public DataSourceEntity getOne(String id) {

        return dataSourceMapper.getOne(id);

    }

    @Transactional
    @Override
    public void add(DataSourceEntity entity) {

        dataSourceMapper.add(entity);

        if(entity.getDatasourceId() != null){


            DataSource dataSource = this.cast(entity);

            if(dataSource != null){

                log.info("添加数据源id={}",entity.getDatasourceId());


                dynamicDataSource.addDataSource(entity.getDatasourceId(),dataSource);

            }

        }

    }

    @Transactional
    @Override
    public void delete(String id) {
        dataSourceMapper.delete(id);

        log.info("删除数据源id={}",id);

        dynamicDataSource.remove(id);

    }


    @Transactional
    @Override
    public void updateById(DataSourceEntity entity) {

        if(entity.getDatasourceId() == null){

            throw new IllegalArgumentException("DataSourceId为null");
        }

        dataSourceMapper.updateById(entity);

        DataSource dataSource = this.cast(entity);

        if(dataSource != null){

            log.info("更新数据源id={}",entity.getDatasourceId());

            dynamicDataSource.addDataSource(entity.getDatasourceId(),dataSource);

        }


    }

    @Override
    public boolean test(DataSourceEntity entity) {

        String errMsg = null;

        String url = entity.getDatasourceUrl();

        String username = entity.getDatasourceUsername();

        String password = entity.getDatasourcePassword();

        String driver = entity.getDatasourceDriver();


        do{

            if(StringUtils.isEmpty( driver)){

                errMsg = "数据源驱动为空";

                break;
            }

            if(StringUtils.isEmpty(password)){
                errMsg = "数据源密码为空";

                break;
            }

            if(StringUtils.isEmpty(url)){

                errMsg = "数据源url为空";

                break;
            }

            if(StringUtils.isEmpty(username)){

                errMsg = "数据源用户名为空";

                break;
            }

            try {
                Class.forName(driver);
            } catch (ClassNotFoundException e) {
                //e.printStackTrace();
                errMsg = "数据源驱动加载失败";

                break;
            }


            try {
                Connection connection = DriverManager.getConnection(url,username,password);

                if(connection != null){


                    connection.close();

                    return true;

                }else{

                    errMsg = "数据库连接获取失败,请检查参数是否正确";
                    break;
                }

            } catch (SQLException e) {
               // e.printStackTrace();

                errMsg = e.getLocalizedMessage();

                break;
            }


        }while (false);


        throw new IllegalArgumentException(errMsg);


    }

    @Override
    public DataSource cast(DataSourceEntity ds)  {

        if(ds == null){
            return null;
        }

        //TODO 后续 druid其他参数设置

        String id = ds.getDatasourceId();

        String url = ds.getDatasourceUrl();

        String username = ds.getDatasourceUsername();

        String password = ds.getDatasourcePassword();

        String driver = ds.getDatasourceDriver();


        do{

            if(StringUtils.isEmpty(url)){

                log.info("数据源id={},url为空",id);

                break;
            }


            if(StringUtils.isEmpty(username)){

                log.info("数据源id={},username为空",id);

                break;
            }


            if(StringUtils.isEmpty(password)){

                log.info("数据源id={},password为空",id);

                break;
            }


            if(StringUtils.isEmpty(driver)){

                log.info("数据源id={},driverClassName为空",id);

                break;
            }


            DruidDataSource druidDataSource = new DruidDataSource();


            druidDataSource.setUrl(url);

            druidDataSource.setPassword(password);

            druidDataSource.setUsername(username);

            druidDataSource.setDriverClassName(driver);

            try {

                druidDataSource.init();


                return druidDataSource;

            }catch (Exception e){

                log.info("数据源id={} 初始化失败",id);
            }

        }while (false);


        return null;
    }

    @Override
    public boolean avaiable(String id) {



        DynamicDataSource dataSource = (DynamicDataSource) dynamicDataSource;


        return dataSource.avaiable(id);


    }


}
